package com.yunzheng.interceptor;


import com.yunzheng.common.BaseResult;
import com.yunzheng.constants.SystemConstants;
import com.yunzheng.enums.ResultStatuesEnums;
import com.yunzheng.redis.RedisManager;
import com.yunzheng.util.MapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author: 郭思良
 * @date: 2020/3/11 9:14
 */

@Slf4j
public class MyShiroFilter extends FormAuthenticationFilter {

    public <T> T getBean(Class<T> clazz, HttpServletRequest request){
        WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return applicationContext.getBean(clazz);
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        Subject subject = getSubject(request,response);
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse) response;

        RedisManager redisManager = getBean(RedisManager.class,req);

        String token = req.getHeader(SystemConstants.TOKEN);

        //没有传token
        if (StringUtils.isBlank(token)){
            res.setCharacterEncoding("UTF-8");
            res.setContentType("application/json");
            res.getWriter().print(MapperUtil.obj2json(BaseResult.notOk(ResultStatuesEnums.NOT_LOGIN)));
            return false;
        }

        String userId = String.valueOf(redisManager.get(token));
        if (StringUtils.isBlank(userId)){
            res.setCharacterEncoding("UTF-8");
            res.setContentType("application/json");
            res.getWriter().print(MapperUtil.obj2json(BaseResult.notOk(ResultStatuesEnums.BAD_TOKEN)));
            return false;
        }

        if (!subject.isAuthenticated()){
            res.setCharacterEncoding("UTF-8");
            res.setContentType("application/json");
            res.getWriter().print(MapperUtil.obj2json(BaseResult.notOk(ResultStatuesEnums.BAD_TOKEN)));
            return false;
        }

        return true;
    }
}
